package com.yitiao.socket.chatroom.demo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws Exception {
        ServerSocket server = new ServerSocket(8889);
        System.out.println("server is established:[8888]");

        Socket socket = server.accept();
        System.out.printf("connect to client:[%s]%n", socket.getPort());

        // 读取客户端的消息
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));   // 装饰器模式
        // 给客户端发消息
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

        String line = reader.readLine();
        if (line != null) {
            System.out.printf("client[%s] send message is:[%s]%n%n", socket.getPort(), line);
            // 自动回复
            writer.write("server back:[" + line + "]\n");
            writer.flush();
        }

        socket.close();

    }
}
